<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/02/14} {11:51} 
 */

namespace wanghua\general_utility_tools_php\log;

/**
 * 日志驱动
 *
 * only for thinkphp!
 *
 * eg:
 *
    $dr = new Driver();
    //$dr->setDriver('file');
    $dr->write(['start'=>11]);

    $dr->write(['end'=>222]);

    $dr->write(['result'=>333]);
    $dr->flush();//must
 *
 * Class Driver
 * @package wanghua\general_utility_tools_php\log
 */
class Driver
{
    private $driver;

    private $lib_path = '';//驱动路径

    protected $static = null;

    public function __construct(string $driver='')
    {
        //driver
        $sys_log_type = $driver?$driver:\think\Config::get('sys_log_type');
        //default driver
        $this->driver = isset($sys_log_type)&&$sys_log_type!=''?$sys_log_type:'file';
        //init driver
        $this->initDriver();
    }

    /**
     * desc：choose driver
     *
     * author：wh
     * @param string $driver
     */
    function setDriver(string $driver){
        //重新设置驱动
        $this->driver = $driver;
        //init driver
        $this->initDriver();
    }

    /**
     * desc：get driver name
     *
     * author：wh
     * @return string
     */
    function getDriverName(){
        return $this->driver;
    }
    /**
     * desc：
     * author：wh
     */
    private function initDriver(){
        $this->driver = $this->driverPath().ucfirst($this->driver);
        $this->static = new $this->driver;
    }

    /**
     * desc：设置日志路径
     * author：wh
     * @param string $logDir
     */
    function setLogDir(string $logDir){
        $this->static->setLogDir($logDir);
    }

    function getLogDir(){
        return $this->static->getLogDir();
    }

    /**
     * desc：set driver lib path
     *
     * author：wh
     * @param $lib_path
     */
    function setLibPath($lib_path){
        $this->lib_path = $lib_path;
    }

    /**
     * desc：init
     *
     * author：wh
     * @return string
     */
    private function driverPath(){
        if($this->lib_path) return $this->lib_path;
        return 'wanghua\general_utility_tools_php\log\driver\\';
    }

    /**
     * desc：group data
     *
     * author：wh
     * @param $data
     */
    function write($data){

        $this->static->write($data);
    }

    /**
     * desc：output data
     *
     * author：wh
     * @return mixed
     */
    function flush(){

        return $this->static->flush();
    }
}